package com.muqi.app.qlearn.student;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapTouchListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.muqi.app.modle.bean.BMapAddress;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.student.R;

public class BMapActivity extends BaseFragmentActivity implements OnClickListener, 
	OnEditorActionListener {
	public static final String BMAP_SELECT_ACTION = "SelectAddress";
	public static final String BMAP_SELECT_DATA = "BMapAddress";
	private EditText myAddress;
	private RelativeLayout btn_save;
	private Button my_location;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	// 定位相关
	private LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;
	private BitmapDescriptor mCurrentMarker;
	// 当前经纬度
	private double mLantitude = 0;
	private double mLongtitude = 0;
	private LatLng mLoactionLatLng;
	boolean isFirstLoc = true;// 是否首次定位
	private String address = "";
	// MapView中央对于的屏幕坐标
	private Point mCenterPoint = null;
	// 地理编码
	private GeoCoder mGeoCoder = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.aty_bmap_select_address);
	}
	
	@Override
	protected void onInit() {
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		btn_save = (RelativeLayout) findViewById(R.id.btn_confirm);
		btn_save.setOnClickListener(this);
		my_location = (Button) findViewById(R.id.btn_myLoaction);
		my_location.setOnClickListener(this);
		myAddress = (EditText) findViewById(R.id.bmap_address_et);
		myAddress.setOnEditorActionListener(this);
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			String searchStr = myAddress.getText().toString();
			// 地理位置编码
			if(!TextUtils.isEmpty(searchStr)){
				mGeoCoder.geocode(new GeoCodeOption().city("").address(searchStr));
			}
			return true;
		}
		return false;
	}

	@Override
	protected void onData() {
		mCurrentMode = LocationMode.NORMAL;
		mCurrentMarker = null;
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
		mBaiduMap.setMapStatus(msu);
		mBaiduMap.setOnMapTouchListener(touchListener);
		// 初始化当前MapView中心屏幕坐标，初始化当前地理坐标
		mCenterPoint = mBaiduMap.getMapStatus().targetScreen;
		mLoactionLatLng = mBaiduMap.getMapStatus().target;
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setIsNeedAddress(true);
		mLocClient.setLocOption(option);
		mLocClient.start();
		// 地理编码
		mGeoCoder = GeoCoder.newInstance();
		mGeoCoder.setOnGetGeoCodeResultListener(GeoListener);
	}

	public void turnBack() {
		// 实现动画跳转
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(mLoactionLatLng);
		mBaiduMap.animateMapStatus(u);
		mBaiduMap.clear();
		// 发起反地理编码检索
		mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption()).location(mLoactionLatLng));
	}
	
	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			MyLocationData data = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					.latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(data);
			mLantitude = location.getLatitude();// 经度
			mLongtitude = location.getLongitude();// 纬度
			mLoactionLatLng = new LatLng(mLantitude, mLongtitude);
			// 发起反地理编码检索
			mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption()).location(mLoactionLatLng));
			myAddress.setText(location.getAddrStr());
			
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
		}
	}

	// 地图触摸事件监听器
	OnMapTouchListener touchListener = new OnMapTouchListener() {
		@Override
		public void onTouch(MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if (mCenterPoint == null) {
					return;
				}
				// 获取当前MapView中心屏幕坐标对应的地理坐标
				LatLng currentLatLng;
				currentLatLng = mBaiduMap.getProjection().fromScreenLocation(mCenterPoint);
				// 发起反地理编码检索
				mGeoCoder.reverseGeoCode((new ReverseGeoCodeOption()).location(currentLatLng));
			}
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_confirm:
			if(mLantitude==0 || mLongtitude==0){
				mLocClient.start();
				return;
			}
			if(TextUtils.isEmpty(myAddress.getText().toString())){
				ShowToast.showShort(this, "请选择地址");
				return;
			}
			
			BMapAddress selectAdress = new BMapAddress();
			selectAdress.setLat(mLantitude);
			selectAdress.setLng(mLongtitude);
			selectAdress.setBMapAdress(myAddress.getText().toString());
			Intent intent = new Intent();
			intent.setAction(BMAP_SELECT_ACTION);
			intent.putExtra(BMAP_SELECT_DATA, selectAdress);
			setResult(RESULT_OK, intent);
			//sendBroadcast(intent);
			finish();
			break;
		case R.id.btn_myLoaction:
			turnBack();
			break;
		default:
			break;
		} 
	}

	// 地理编码监听器
	OnGetGeoCoderResultListener GeoListener = new OnGetGeoCoderResultListener() {
		
		public void onGetGeoCodeResult(GeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				// 没有检索到结果
				showToast("未找到该地址,换个地址搜索试试");
			} else {
				// 获取地理编码结果
				mLantitude = result.getLocation().latitude;// 经度
				mLongtitude = result.getLocation().longitude;// 纬度
				mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result.getLocation()));
				address = result.getAddress();
				myAddress.setText(address);
			}
		}

		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				// 没有找到检索结果
			} else {// 获取反向地理编码结果
				// 当前位置信息
				mLantitude = result.getLocation().latitude;// 经度
				mLongtitude = result.getLocation().longitude;// 纬度
				address = result.getAddress();
				myAddress.setText(address);
			}
		}
	};

	@Override
	protected void onDestroy() {
		if (mLocClient != null) {
			mLocClient.stop();
		}
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mMapView.onPause();
		if (mLocClient != null) {
			mLocClient.stop();
		}
	}
	
	public void finish(View view){
		finish();
	}
}
